package com.cy.lib.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by CY on 2015/8/29.
 *
 * @author CY
 * @title 图片居中
 */
public class CenterDrawableTextView extends TextView {
    public CenterDrawableTextView(Context context) {
        super(context);
    }

    public CenterDrawableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CenterDrawableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Drawable[] drawables = getCompoundDrawables();
        if (drawables != null) {
            Drawable drawableLeft = drawables[0];
            if (drawableLeft == null) {
                drawableLeft = drawables[2];//right，左右原理相同
            }
            if (drawableLeft != null) {
                final float textWidth = getPaint().measureText(getText().toString());
                final int drawablePadding = getCompoundDrawablePadding();
                final int drawableWidth = drawableLeft.getIntrinsicWidth();
                final float bodyWidth = textWidth + drawableWidth + drawablePadding;
                float padding = (getWidth() - bodyWidth) / 2;
                setPadding((int) padding, getPaddingTop(), (int) padding, getPaddingBottom());
            }

            Drawable drawableTop = drawables[1];
            if (drawableTop == null) {
                drawableTop = drawables[3];//bottom,上下原理相同
            }
            if (drawableTop != null) {
                float textHeight = 0f;
                int drawableHeight = drawableTop.getBounds().height();
                if (!TextUtils.isEmpty(getText())) {
//                    Rect rect = textRect(getText().toString());
                    textHeight = getTextSize()* getLineCount();;//rect.height() * getLineCount();
                }

                float bodyHeight = textHeight + drawableHeight + getCompoundDrawablePadding();

                int padding = (int) ((getHeight() - bodyHeight) / 2);
                setPadding(getPaddingLeft(), padding, getPaddingRight(), padding-8);//小米note底部有偏差-8
            }
        }

    }

    private Rect textRect(String text) {
        Rect rect = new Rect();
        getPaint().getTextBounds(text, 0, text.length(), rect);
        return rect;
    }

}
